package com.atguigu.gmall.list.listener;

import com.atguigu.gmall.list.service.GoodsService;
import com.atguigu.gmall.mq.mqconst.Mqconst;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ProductListener {

    @Autowired
    private GoodsService goodsService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue.goods.import", durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = Mqconst.RABBIT_EXCHANGE_GOODS, durable = "true", autoDelete = "false"),
            key = {Mqconst.RABBIT_ROUTING_KEY_GOODS_IMPORT}
    ))
    public void goodsImport(Message message, Channel channel,Long skuId) throws IOException {
        try {
            goodsService.saveGoods(skuId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            if (message.getMessageProperties().getRedelivered()) {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            }else{
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue.goods.report", durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = Mqconst.RABBIT_EXCHANGE_GOODS, durable = "true", autoDelete = "false"),
            key = {Mqconst.RABBIT_ROUTING_KEY_GOODS_REMOVE}
    ))
    public void goodsReport(Message message, Channel channel,Long skuId) throws IOException {
        try {
            goodsService.removeGoods(skuId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            if (message.getMessageProperties().getRedelivered()) {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            }else{
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }


}
